package com.gosling.cloudspace.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.SM3;

import java.nio.charset.StandardCharsets;

/**
 * @author lihonglin
 * @date 2024/1/26 14:37
 */
public class SM3Util {
    private static final byte[] SALT = "SM3&#%$@!(%)".getBytes(StandardCharsets.UTF_8);
    private static final SM3 INSTANCE = SM3.create();

    /**
     * 计算SM3摘要值
     *
     * @param content 原文
     * @return 摘要值，对于SM3算法来说是32字节
     */
    public static String sm3Digest(String content) {
        if (StrUtil.isBlank(content)){
            throw new NullPointerException("the content is not empty!");
        }
        return INSTANCE.setSalt(SALT).digestHex(content);
    }

    /**
     * 验证摘要
     *
     * @param content 原文
     * @param sm3Hash 摘要值
     * @return 返回true标识验证成功，false标识验证失败
     */
    public static boolean verify(String content, String sm3Hash) {
        if (StrUtil.isBlank(content)){
            throw new NullPointerException("the content is not empty!");
        }
        String newHash = sm3Digest(content);
        return newHash.equalsIgnoreCase(sm3Hash);
    }

}